package org.edu.modules.change.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.base.controller.BaseController;
import org.edu.common.system.query.QueryGenerator;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.change.entity.VeHrChange;
import org.edu.modules.change.service.IVeHrChangeService;
import org.edu.modules.teacher.service.IBaseTeacherService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: ve_hr_change
 * @Author: jeecg-boot
 * @Date: 2021-03-11
 * @Version: V1.0
 */
@Api(tags = "ve_hr_change")
@RestController
@RequestMapping("/hr/change/veHrChange")
@Slf4j
public class VeHrChangeController extends BaseController<VeHrChange, IVeHrChangeService> {
    @Autowired
    private IVeHrChangeService veHrChangeService;
    @Autowired
    private IBaseTeacherService baseTeacherService;

    /**
     * 分页列表查询
     *
     * @param veHrChange
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "ve_hr_change-分页列表查询")
    @ApiOperation(value = "ve_hr_change-分页列表查询", notes = "ve_hr_change-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(VeHrChange veHrChange,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<VeHrChange> queryWrapper = QueryGenerator.initQueryWrapper(veHrChange, req.getParameterMap());
        Page<VeHrChange> page = new Page<VeHrChange>(pageNo, pageSize);
        IPage<VeHrChange> pageList = veHrChangeService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param veHrChange
     * @return
     */
    @AutoLog(value = "ve_hr_change-添加")
    @ApiOperation(value = "ve_hr_change-添加", notes = "ve_hr_change-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody VeHrChange veHrChange) {


        /*// 获取当前登陆用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 设置操作人
        veHrChange.setCreateuserid(sysUser.getId());
        veHrChange.setCreateusername(sysUser.getRealname());*/

        // 从前端获取设置操作人的id和名称


        veHrChangeService.save(veHrChange);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param veHrChange
     * @return
     */
    @AutoLog(value = "ve_hr_change-编辑")
    @ApiOperation(value = "ve_hr_change-编辑", notes = "ve_hr_change-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody VeHrChange veHrChange) {
        veHrChangeService.updateById(veHrChange);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ve_hr_change-通过id删除")
    @ApiOperation(value = "ve_hr_change-通过id删除", notes = "ve_hr_change-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        veHrChangeService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "ve_hr_change-批量删除")
    @ApiOperation(value = "ve_hr_change-批量删除", notes = "ve_hr_change-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.veHrChangeService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ve_hr_change-通过id查询")
    @ApiOperation(value = "ve_hr_change-通过id查询", notes = "ve_hr_change-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        VeHrChange veHrChange = veHrChangeService.getById(id);
        if (veHrChange == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(veHrChange);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param veHrChange
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, VeHrChange veHrChange) {
        return super.exportXls(request, veHrChange, VeHrChange.class, "变动表");
    }

    /**
     * exportXlsTemplate
     */
    @RequestMapping(value = "/exportXlsTemplate")
    public ModelAndView exportXlsTemplate(HttpServletRequest request, VeHrChange veHrChange) {
        return super.exportXlsTemplate(request, veHrChange, VeHrChange.class, "变动表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<VeHrChange> list = ExcelImportUtil.importExcel(file.getInputStream(), VeHrChange.class, params);
                //update-begin-author:taoyan date:20190528 for:批量插入数据
                long start = System.currentTimeMillis();
                Map<String, String> map = baseTeacherService.listTeacherUserIdAndWorkNo();
                for (VeHrChange veHrChange : list) {
                    String teacherId = MapUtils.getString(map, veHrChange.getGh(), "default");
                    if (StrUtil.equals(teacherId, "default")) {
                        return Result.error("不存在工号为" + veHrChange.getGh() + "的用户，请核对！");
                    }
                    veHrChange.setTeacherid(teacherId);
                }
                veHrChangeService.saveBatch(list);
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }


}
